package com.geek.novel.activity.book

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.adapter.BookSearchListAdapter
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookRead
import com.geek.novel.network.RslHandler
import com.geek.novel.services.NovelService
import com.geek.novel.services.SearchHistoryRepository
import com.geek.novel.utils.CommUtil
import com.geek.novel.utils.FormatUtil
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.*
import kotlinx.android.synthetic.main.activity_book_search.*
import kotlinx.android.synthetic.main.activity_book_search_history.*


class BookSearchActivity: TitleBarActivity() , RslHandler {

	/**书籍列表*/
	private var books: ArrayList<BookRead> = ArrayList()

	/**搜索的关键字*/
	private var keyword: String = ""
	/**搜索的分类*/
	private var category: Int? = null

	/**当前页码，下标从0开始*/
	private var pageNo: Int = 0
	/**每页显示条数*/
	private var pageSize: Int = 10

	/**书籍列表的适配器*/
	private lateinit var listViewAdapter: BookSearchListAdapter

	/**小说服务*/
	private lateinit var novelService: NovelService

	/**搜索历史的服务*/
	private val searchHistoryRepository = SearchHistoryRepository.getInstance()

	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_book_search)
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_book_search)

		//设置背景为白色
		super.setBackgroundColor(Color.WHITE)

		//初始化服务对象
		novelService = NovelService(this)

		//显示历史记录的列表
		this.showSearchHistory()

		//初始化搜索的关键字和分类
		this.initSearchKeyword()

		//初始化下拉刷新功能
		this.initRefreshLayout()

		//初始化列表
		this.initListView()

		//显示搜索框
		super.showSearchBox()

		//获取热搜词
		this.queryBookSearchHotKey()

		//获取搜索历史
		this.queryBookSearchHistory()

	}

	/**初始化搜索的关键字和分类*/
	@SuppressLint("SetTextI18n")
	private fun initSearchKeyword(){
		val bundle = intent.extras?:Bundle()
		val category = bundle.getString("category")
		val categoryStr = bundle.getString("categoryStr")
		if(!TextUtils.isEmpty(category)){
			this.category = FormatUtil.isNullToIntZero(category)
			super.setSearchHint("搜索${categoryStr}")
			tv_book_search_no_result.text = "暂无搜索结果(${categoryStr})"
		}
		//设置搜索关键字，目前没有作用，未来再说
		val keywordStr = bundle.getString("keyword")
		this.setSearchKey(keywordStr)
	}

	/**设置搜索的关键字到输入框里面，注意，这里不会发起搜索，需要手动调一下search方法*/
	private fun setSearchKey(keywordStr: String?){
		if(!TextUtils.isEmpty(keywordStr)){
			this.keyword = keywordStr!!
			super.setSearchText(keyword)
		}
	}

	/**发起搜索，注意，这里面不会为keyword赋值*/
	private fun search(){
		//隐藏历史记录的列表
		this.hideSearchHistory()

		//发起搜索
		LoadingDialogUtil.getInstance().showLoading("搜索中...")
		this.resetSearchBook()
		this.searchBook()

		//记录搜索历史
		this.saveSearchHistory(this.keyword)

		//开启下拉刷新和滚动加载
		this.toggleRefreshLayoutEnable(true)
	}

	private fun queryBookSearchHotKey(){
		LoadingDialogUtil.getInstance().showLoading("加载中...")
		this.novelService.queryBookSearchHotKey()
	}

	/**初始化搜索的热搜词*/
	private fun initSearchHotKey(hotKeyList: List<BookSearchHotKeyVo>){
		if(hotKeyList.isEmpty()){//隐藏热搜词
			toggleHistoryHotKeyVisible(false)
			return
		}
		toggleHistoryHotKeyVisible(true)

		//显示热搜词
		ly_history_hotkey.removeAllViews()
		hotKeyList.forEach { item ->
			if(TextUtils.isEmpty(item.hotkey)){
				return@forEach
			}
			val textView = this.createHistoryItem(item.hotkey!!)
			this.bindHistoryItemClickEvent(textView)
			ly_history_hotkey.addView(textView)
		}
	}

	/**设置历史搜索的属性样式*/
	private fun createHistoryItem(text: String): TextView{
		val textView = TextView(this)
		textView.text = text
		val paddingTB = CommUtil.dip2px(4F).toInt()
		val paddingLR = CommUtil.dip2px(10F).toInt()
		textView.setPadding(paddingLR, paddingTB, paddingLR, paddingTB)
		textView.setBackgroundResource(R.drawable.bg_book_search_history_item)
		return textView
	}

	/**绑定历史搜索的点击事件*/
	private fun bindHistoryItemClickEvent(view: View){
		view.setOnClickListener{
			it as TextView
			val text = it.text.toString()
			this.setSearchKey(text)
			this.search()
		}
	}

	/**获取搜索历史*/
	private fun queryBookSearchHistory(){
		ly_history_search.removeAllViews()
		val list = searchHistoryRepository.list()
		list.forEach { item ->
			if(TextUtils.isEmpty(item.searchText)){
				return@forEach
			}
			val textView = this.createHistoryItem(item.searchText)
			this.bindHistoryItemClickEvent(textView)
			ly_history_search.addView(textView)
		}
	}

	/**清除搜索历史*/
	private fun clearSearchHistory(){
		searchHistoryRepository.clearData()
		this.queryBookSearchHistory()
	}

	/**保存搜索历史*/
	private fun saveSearchHistory(text: String){
		searchHistoryRepository.save(text)
	}

	/**切换热搜词的显示隐藏*/
	private fun toggleHistoryHotKeyVisible(show: Boolean){
		val visible = if(show) View.VISIBLE else View.GONE
		ly_history_hotkey_title.visibility = visible
		ly_history_hotkey.visibility = visible
	}

	/**显示历史记录的列表*/
	private fun showSearchHistory(){
		ly_book_search_history.visibility = View.VISIBLE
		ly_book_search_no_result.visibility = View.GONE
		rv_books_search.visibility = View.GONE
	}

	/**隐藏历史记录的列表*/
	private fun hideSearchHistory(){
		ly_book_search_history.visibility = View.GONE
	}

	/**触发搜索事件*/
	override fun onSearchBtnClick(view: View, text: Editable) {
		this.keyword = text.toString()
		this.search()
	}

	/**附加控件*/
	override fun attachViewChild() {
	}

	/**绑定事件*/
	override fun bindEventChild() {
		//清除搜索历史的按钮事件
		btn_history_clear.setOnClickListener(this)
	}

	/**重置搜索下标*/
	private fun resetSearchBook(){
		book_search_refresh_layout.resetNoMoreData()
		this.pageNo = 0
		this.books.clear()
	}

	/**搜索*/
	private fun searchBook(){
		LogCatUtil.d("???", "当前页码：$pageNo")
		novelService.bookSearch(keyword, category, Pager.of(pageNo, pageSize))
		pageNo++
	}

	/**处理搜索结果*/
	private fun handleSearchResult(vo: BookSearchVo){
		try {
			val pager = vo.result ?: throw Exception("获取查询结果异常！")
			val records = pager.records ?: throw Exception("获取查询结果异常！")
			books.addAll(records)
			listViewAdapter.notifyDataSetChanged()
		} catch (e: Exception) {
			ToastUtils.toast(e.message)
			LogCatUtil.e("???", e.message, e)
		}
		this.checkBookEmpty()
	}

	/**是否打开下拉刷新和滚动加载*/
	private fun toggleRefreshLayoutEnable(enable: Boolean){
		book_search_refresh_layout.setEnableRefresh(enable)
		book_search_refresh_layout.setEnableLoadMore(enable)
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		//不开启下拉刷新和滚动加载,等到搜索再开启
		this.toggleRefreshLayoutEnable(false)

		book_search_refresh_layout.setRefreshHeader(book_search_classics_header)
		book_search_refresh_layout.setRefreshFooter(book_search_classics_footer)
		//下拉刷新
		book_search_refresh_layout.setOnRefreshListener {
			//隐藏历史记录的列表
			this.hideSearchHistory()
			//重置搜索下标
			this.resetSearchBook()
			//发起搜索
			this.searchBook()
		}
		//滚动加载
		book_search_refresh_layout.setOnLoadMoreListener{
			this.searchBook()
		}
	}


	/**初始化列表*/
	private fun initListView(){
		//添加适配器
		listViewAdapter = BookSearchListAdapter(this, books)
		listViewAdapter.initListView(rv_books_search)
	}


	/**检查书籍列表是否为空*/
	private fun checkBookEmpty(): Boolean{
		//书架列表为空的情况，添加书籍按钮
		if(books.isEmpty()){
			ly_book_search_no_result.visibility = View.VISIBLE
			rv_books_search.visibility = View.GONE
		}else{
			ly_book_search_no_result.visibility = View.GONE
			rv_books_search.visibility = View.VISIBLE
		}
		return books.isEmpty()
	}


	override fun clickEvent(id: Int, v: View) {
		when(id){
			//清除历史搜索的按钮事件
			R.id.btn_history_clear->{
				this.clearSearchHistory()
			}
		}
	}

	override fun onError(code: Int, err: ApiErrorResult) {
		when(code){
			//获取热搜词
			Constant.HTTP_KEY_APP_QUERY_BOOK_SEARCH_HOT_KEY->{
				LoadingDialogUtil.getInstance().dismiss()
			}
			//搜索结果
			Constant.HTTP_KEY_APP_BOOK_SEARCH->{
				LoadingDialogUtil.getInstance().dismiss()
				book_search_refresh_layout.finishRefresh(false)
				book_search_refresh_layout.finishLoadMore(false)
			}
		}
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取热搜词
			Constant.HTTP_KEY_APP_QUERY_BOOK_SEARCH_HOT_KEY->{
				LoadingDialogUtil.getInstance().dismiss()

				val hotKeyList = result.getList(BookSearchHotKeyVo::class.java)

				this.initSearchHotKey(hotKeyList)
			}
			//搜索结果
			Constant.HTTP_KEY_APP_BOOK_SEARCH->{
				LoadingDialogUtil.getInstance().dismiss()
				val bookSearchVo = result.getData() as BookSearchVo
				this.handleSearchResult(bookSearchVo)
				//处理下拉刷新
				book_search_refresh_layout.finishRefresh(true)
				//处理滚动加载
				val noMoreData = bookSearchVo.result!!.totalPages-1 < pageNo
				book_search_refresh_layout.finishLoadMore(0, true, noMoreData)
			}
		}
	}


}